class MyPageHeader extends BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        super(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
                returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl);
        this.hasFilterValue = true;
        this.checkUrl = "/purchase/po/header/check.html";
        this.uncheckUrl = "/purchase/po/header/uncheck.html";
    }
    GetFilterValue() {
        let item = {};
        item['HeaderId'] = parseInt(this.dataId);
        item['CurrentUserId'] = parseInt($("#UserId").val());
        item['WorkFlowId'] = $("#WorkFlowId").val() === '' ? 0 : parseInt($("#WorkFlowId").val());
        item['PageIndex'] = 1;
        item['Flag'] = 0;       // 表示要读取包括调达表等其他信息
        item['Limit'] = parseInt($("#page-size").val());
        item['Limit02'] = 10;   // 以下两个参数完全是为了满足函数需求，实际上没有任何意义。
        item['Limit03'] = 10;

        return item;
    }
    FillData(data) {
        let item = data.HeaderEntity;
        $("#HeaderId").val(item.headerId);
        let _po_type = "";
        switch (item.billTypeId) {
            case 1:
                _po_type = "采购合同";
                break;
            case 2:
                _po_type = "库存采购";
                break;
            case 3:
                _po_type = "成本合同";
                break;
        }
        $("#PoNo").text(item.poNo + "（采购类型：" + _po_type + "）");
        $("#SupplierName").text(item.supplierName + "（编号：" + (item.supplierNo === null ? "" : item.supplierNo) + "）");
        $("#Attn").text(item.attn);
        $("#Fax").text(item.fax);
        $("#CurrencyId").text(item.currencyId);
        $("#CurrencyName").text(item.currencyName);
        $("#DateOfSigning").text(item.dateOfSigning);
        $("#DateOfArrival").text(item.dateOfArrival);
        $("#FabricWidth").text(item.fabricWidth);
        $("#GramWeight").text(item.gramWeight);
        $("#QuantityOfLimited").html(item.quantityOfLimited === null ? "" : item.quantityOfLimited.replace(/\n/g, '<br/>'));
        $("#TermsOfPayment").text(item.termsOfPayment);
        //$("#QualityStandard").html(item.qualityStandard === null ? "" : item.qualityStandard.replace(/\n/g, '<br/>'));
        $("#QualityStandard").html(item.qualityStandard === null ? "" : item.qualityStandard);
        $("#Description").html(item.description === null ? "" : item.description.replace(/\n/g, '<br/>'));
        $("#EnterpriseName").text(item.enterpriseName);
        $("#PurchasedBy").text(item.purchasedBy);
        $("#PurchasedByName").text(item.purchasedByName);
        $("#UpdatedBy").text(item.updatedByName + "　（" + item.updatedDate + "）");

        // 最后的审核人、审核日期
        $("#CheckedBy").text(item.checkedBy);
        $("#CheckedByName").val(item.checkedByName);
        //$("#CheckedDate").text(item.checkedDate === null ? '' : item.checkedDate);
        $("#CheckedStatus").val(item.checkedStatus);
        $('#FlowOrderNo').val(item.flowOrderNo);

        // 设置订单的材料列表
        _InstancePageLines.SetPoMaterialList(data.PoMaterialList);
        // 合同明细表             
        _InstancePageLines.BuildDataTable(data.PoLinesList);

        this.currentTaskPrivileges = item.currentTaskPrivileges;
        this.nextTaskPrivileges = item.nextTaskPrivileges;
        this.unCheckFlag = item.unCheckFlag;
        this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
        });
    }
    DoCheck() {
        let item = {};
        item['HeaderId'] = parseInt($("#HeaderId").val());
        item['WorkFlowId'] = parseInt($("#WorkFlowId").val());
        item['NodeOrder'] = parseInt($("#FlowOrderNo").val());
        item['CheckedBy'] = parseInt($("#UserId").val());
        item['IsCheckCurrentNode'] = this.currentTaskPrivileges === 0 ? 0 : 1;
        item['PageIndex'] = $("abbr.page_indicator_block,#wrapper__navbar").attr("_msh_page");
        item['Limit'] = parseInt($("#page-size").val());

        $.ajax({
            type: "POST",
            url: parent.basePath + this.checkUrl,
            timeout: 30 * 1000,
            data: JSON.stringify(item),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: () => {
            }
        }).done(data => {
            let item = data.HeaderEntity;
            // 最后的审核人、审核日期
            $("#CheckedBy").val(item.checkedBy);
            $("#CheckedByName").val(item.checkedByName);
            $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
            $("#CheckedStatus").val(item.checkedStatus);
            $('#FlowOrderNo').val(item.flowOrderNo);
            this.currentTaskPrivileges = item.currentTaskPrivileges;
            this.nextTaskPrivileges = item.nextTaskPrivileges;
            this.unCheckFlag = item.unCheckFlag;

            // 设置画面各个元素状态
            this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
            });
        }).fail(function (data) {
            ajaxError(data, 1);
        }).always(function ( ) {
        });
    }
    Uncheck() {
        let item = {};
        item['HeaderId'] = parseInt($("#HeaderId").val());
        item['WorkFlowId'] = parseInt($("#WorkFlowId").val());
        item['NodeOrder'] = parseInt($("#FlowOrderNo").val());
        item['CheckedBy'] = parseInt($("#UserId").val());
        item['PageIndex'] = $("abbr.page_indicator_block,#wrapper__navbar").attr("_msh_page");
        item['Limit'] = parseInt($("#page-size").val());

        $.ajax({
            type: "POST",
            url: parent.basePath + this.uncheckUrl,
            timeout: 30 * 1000,
            data: JSON.stringify(item),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: () => {
            }
        }).done(data => {
            let item = data.HeaderEntity;
            // 最后的审核人、审核日期
            $("#CheckedBy").val(item.checkedBy);
            $("#CheckedByName").val(item.checkedByName);
            $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
            $("#CheckedStatus").val(item.checkedStatus);
            $('#FlowOrderNo').val(item.flowOrderNo);

            this.currentTaskPrivileges = item.currentTaskPrivileges;
            this.nextTaskPrivileges = item.nextTaskPrivileges;
            this.unCheckFlag = item.unCheckFlag;

            // 设置画面各个元素状态
            this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
            });
        }).fail(data => {
            ajaxError(data, 1);
        }).always(( ) => {
        });
    }
    ShowPageElement() {
    }
    HidePageElement() {
    }
}

//-----------------------------------------------------------------------------
// 订单明细
//-----------------------------------------------------------------------------
class MyPageLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.orderby = "";
    }
    SetPageSize() {
        $.cookie("po_lines_list_pagesize", $("#page-size").val());
        this.FetchLinesForPage(1);
    }
    // 获取明细表分页信息
    GetFilterValue(pageIndex) {
        if (pageIndex !== 0) {
            $("abbr.page_indicator_block,#wrapper__navbar").attr("_msh_page", pageIndex);
        }

        let item = {};
        item['HeaderId'] = parseInt($.trim($("#HeaderId").val()));
        item['CurrentUserId'] = parseInt($("#UserId").val());     // 当前操作者，用于过滤供应商分组
        item['Limit'] = parseInt($("#page-size").val());          // limit;
        item['PageIndex'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar").attr("_msh_page"));
        if ($("#PoMaterialList").val() !== "-1") {
            item['MaterialNameFilterVal'] = $("#PoMaterialList").val();
        }
        item['OrderBy'] = this.orderby;
        return JSON.stringify(item);
    }
    FetchLinesForPageNoFilter() {
        $("#StyleNoFilterValue").val("");
        $("#MaterialNoFilterValue").val("");
        $("#MaterialNameFilterValue").val("");
        $("#MaterialColourNameFilterValue").val("");

        $("abbr.page_indicator_block,#wrapper__navbar").attr("_msh_page", 1);
        this.FetchLinesForPage(1);
    }
    // 取得引入的订单明细分页信息
    FetchLinesForPage(pageIndex) {
        let _this = this;
        $.ajax({
            type: "POST",
            url: parent.basePath + "/purchase/po/lines/fetchForPage.html",
            timeout: 60 * 1000,
            data: _this.GetFilterValue(pageIndex),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                $("#loading__indicator").show();
            }
        }).done((data) => {
            if (data.Success === true) {
                _this.BuildDataTable(data);
            }
        }).fail((data) => {
            ajaxError(data, 1);
        }).always(() => {
            $("#loading__indicator").hide();
        });
    }
    // 构建明细数据列表
    BuildDataTable(result) {
        let current_page = result.PageIndex;
        // 设置翻页控件
        if (result.TotalPages > 0) {  //总页数
            $("#wrapper__navbar").data("swPagination").options.max_page = result.TotalPages;
        } else {
            $("#wrapper__navbar").data("swPagination").options.max_page = 1;
        }
        if (result.PageIndex > 0) { //当前页数
            $("#wrapper__navbar").data("swPagination").options.current_page = result.PageIndex;
            $("#wrapper__navbar").data("swPagination").setPage(result.PageIndex);
        } else {
            $("#wrapper__navbar").data("swPagination").options.current_page = 1; //当前页数
            $("#wrapper__navbar").data("swPagination").setPage(1);
        }

        // 得到数据列表
        $('#tabData41 tbody').empty();
        $('#tabData42 tbody').empty();
        result = result.DataList;
        if (result === undefined || result === null) {
            this.numCheckbox = 0;
            return false;
        }

        this.numCheckbox = result.length;
        let content_01 = '';
        let content_02 = '';
        for (let i = 0; i < result.length; i++) {
            let id = result[i].linesId;
            let sequence = i + 1 + (current_page - 1) * parseInt($("#page-size").text());
            content_01 += '<tr _mash_id="' + id + '" _supplierId="' + result[i].supplierId + '" _rowFlag="' + result[i].rowFlag + '">';
            if (parseInt(result[i].rowFlag) === 0) {
                content_01 += '<td style="text-align:center;">' + sequence + '</td>';
                content_01 += '<td>' + formatNullData(result[i].styleNo) + '</td>';
                content_01 += '<td class="edited-cell" _mash_old_materialno="' + formatNullData(result[i].materialCode) + '" _mash_materialId="' + result[i].materialId + '" title="供应商：' + formatNullData(result[i].supplierName) + '"supplierName>' + formatNullData(result[i].materialCode) + '</td>';
                content_01 += '<td>' + formatNullData(result[i].materialName) + '</td>';
            }
            // 附加费
            if (parseInt(result[i].rowFlag) === 2) {
                content_01 += '<td style="text-align:center;">' + sequence + '</td>';
                content_01 += '<td colspan="3" style="text-align:center;">附加费</td>';
            }
            content_01 += '</tr>';

            content_02 += '<tr _mash_id="' + id + '">';
            if (parseInt(result[i].rowFlag) === 0) {
                content_02 += '<td>' + formatNullData(result[i].mcolourCode) + '</td>';     // 材料色码
                content_02 += '<td>' + formatNullData(result[i].materialColourName) + '</td>';                  // 材料色
                content_02 += '<td>' + formatNullData(result[i].specification) + '</td>';                       // 规格
                content_02 += '<td style="text-align:center;" _mash_uomid="' + result[i].uomId + '" _mash_mrp_uomid="' + formatNullData(result[i].mdpUomId) + '" _Coefficient="' + formatNullData(result[i].coefficient) + '">' + formatNullData(result[i].uomName) + '</td>';     // _IsCoefficient："0"-不用米转系数，“1”-需要使用系数进行转换。计量单位
                content_02 += '<td>' + formatNullData(result[i].planQuantity) + '</td>';     // 计划数量
                // 损耗
                if (result[i].lossId === null) {
                    content_02 += '<td class="error" title="该材料没有设置订货损耗">&nbsp;</td>';
                } else {
                    content_02 += '<td>' + formatNullData(result[i].sparedQuantity) + '</td>';
                }
                content_02 += '<td _mash_plan_quantity="' + result[i].planQuantity + '">' + formatNullData(result[i].poQuantity === 0 ? null : result[i].poQuantity) + '</td>';  // 采购数量
                content_02 += '<td>' + formatNullData(result[i].unitPrice === null ? null : result[i].unitPrice.toFixed(3)) + '</td>';    // 基础单价
                content_02 += '<td>' + formatNullData(result[i].poUnitPrice === null ? null : result[i].poUnitPrice.toFixed(3)) + '</td>';  // 订货单价
                if (result[i].poUnitPrice > result[i].unitPrice)
                    content_02 += '<td style="text-align:center;">' + '<span class="n2">异常&nbsp;↑</span>' + '</td>';    // 价格异常(高于标准)
                if (result[i].poUnitPrice < result[i].unitPrice)
                    content_02 += '<td style="text-align:center;">' + '<span class="n1">异常&nbsp;↓</span>' + '</td>';    // 价格异常(低于标准)
                if (result[i].poUnitPrice === result[i].unitPrice)
                    content_02 += '<td style="text-align:center;">&nbsp;</td>';    // 价格正常
                content_02 += '<td>' + (result[i].poQuantity * result[i].poUnitPrice).toFixed(2) + '</td>';                             // 金额
                content_02 += '<td style="border-right:none;">' + formatNullData(result[i].description) + '</td>';  // 备注
            }
            // 这是附加费行
            if (parseInt(result[i].rowFlag) === 2) {
                content_02 += '<td colspan="6"></td>';
                content_02 += '<td _mash_plan_quantity="' + result[i].planQuantity + '">' + formatNullData(result[i].poQuantity === 0 ? null : result[i].poQuantity) + '</td>'; // 采购数量
                content_02 += '<td></td>';                                                  // 基础单价
                content_02 += '<td>' + formatNullData(result[i].poUnitPrice === null ? null : result[i].poUnitPrice.toFixed(3)) + '</td>';   // 订货单价
                content_02 += '<td style="text-align:center;">&nbsp;</td>';                // 价格正常
                content_02 += '<td>' + (result[i].poQuantity * result[i].poUnitPrice).toFixed(2) + '</td>';           // 金额
                content_02 += '<td style="border-right:none;">' + formatNullData(result[i].description) + '</td>';    // 备注
            }
            content_02 += '</tr>';

            $("#tabData41 tbody").append(content_01);
            $("#tabData42 tbody").append(content_02);
            content_01 = '';
            content_02 = '';
        }

        setTwoTableRowColor("tabData41", "tabData42");
        $(window).resize();               // 防止因为出现滚动条而造成画面显示问题
    }
    // 设置订单材料下拉列表
    SetPoMaterialList(data) {
        $("#PoMaterialList").empty();
        if (data !== null) {
            let options = [];
            options.push('<option value="-1">-- 按材料过滤 --</option>');
            for (let i = 0; i < data.length; i++) {
                options.push('<option value="', data[i].materialName, '">', data[i].materialName, '</option>');
            }
            $("#PoMaterialList").html(options.join(''));
        } else {
            let options = [];
            options.push('<option value="-1">-- 按材料过滤 --</option>');
            $("#PoMaterialList").html(options.join(''));
        }
    }
    ScrollTo() {
        $('#divH42').scrollLeft($('#divD42').scrollLeft());
        $('#divD41').scrollTop($('#divD42').scrollTop());
    }
    SortTable(order_by) {
        this.orderby = order_by;
        this.FetchLinesForPage(1);
    }
}

var _InstancePageHeader = null;
var _InstancePageLines = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let _dataId = 0;
    let check_list_result = $.cookie("po_check_list_result") === undefined ? "" : $.cookie("po_check_list_result");
    let _pageListData = [];
    if (check_list_result !== "") {
        _pageListData = check_list_result.split(',');

        $("#HeaderId").val(_pageListData[0]);
        _dataId = _pageListData[0];

        $("#rec_total_rows").text(_pageListData.length);
        $("#rec_cur_row").text($.inArray(_dataId, _pageListData) + 1);

        if (_pageListData.length > 0) {
            let index = $.inArray(_dataId, _pageListData);
            if (index === 0) {
                $("#ButPrev").attr("disabled", "disabled");
            } else {
                $("#ButNext").removeAttr("disabled");
            }
            if (index === (_pageListData.length - 1)) {
                $("#ButNext").attr("disabled", "disabled");
            } else {
                $("#ButPrev").removeAttr("disabled");
            }
        }
    } else {
        $("#rec_total_rows").text("1");
        $("#rec_cur_row").text("1");
        $("#HeaderId").val(0);
    }

    _InstancePageHeader = new MyPageHeader(_dataId, 0, 0, 3, _pageListData,
            "/purchase/po/list.html",
            "/purchase/po/header/fetchByKey.html",
            null, null, null);
    _InstancePageLines = new MyPageLines();

    $("#loading__indicator").hide();

    // 设置采购订单明细分页控制
    $("#wrapper__navbar").swPagination({
        link_string: '/?page={page_number}',
        max_page: null,
        paged: function (page) {
            $("abbr.page_indicator_block,#wrapper__navbar").attr("_msh_page", page);
            _InstancePageLines.FetchLinesForPage(page);
        }
    });
    $("abbr.page_indicator_block,#wrapper__navbar").attr("_msh_page", 1);
    /*
     // 设置订单明细表格排序字段
     $("#tabHeader41").wxTableSorter({
     sortList: [[3, 2], [4, 2], [5, 2]], // 第一个表示列的序号，第二个表示排序种类
     headers: {3: {sorter: false}, 4: {sorter: false}, 5: {sorter: false}},
     columnList: [[1, "L.StyleNo, L.ProductColourName, L.UpdatedDate"],
     [2, "M.MaterialCode, L.StyleNo, L.ProductColourName, L.UpdatedDate"],
     [3, "M.MaterialName, L.StyleNo, L.ProductColourName, L.UpdatedDate"]],
     detailList: $("#tabData41"),
     sort: function (orderBy) {
     _InstancePageLines.SortTable(orderBy);
     }
     });
     $("#tabHeader42").wxTableSorter({
     sortList: [[1, 2]], // 第一个表示列的序号，第二个表示排序种类
     headers: {1: {sorter: false}},
     columnList: [[1, "L.MaterialColourName, L.StyleNo, L.ProductColourName, L.UpdatedDate"]],
     detailList: $("#tabData42"),
     sort: function (orderBy) {
     _InstancePageLines.SortTable(orderBy);
     }
     });*/
    // SetSearchWnd();

    _InstancePageHeader.OnPageLoad();
}

function SetSearchWnd() {
    let clazz = 'search--active';

    // 设置引入订单明细的搜索
    let $search = $('#search');
    // 搜索按钮
    $('#search_btn').on('click', function (event) {
        $search.addClass(clazz);
        $search.on(window.transitionProp, function (event) {
            $search.find('input').first().focus();
        });
    });
    // 搜索窗口关闭
    $('#search__form_butclose').on('click', function (event) {
        $search.removeClass(clazz);
    });
}
// 画面大小或者位置移动
function onPageResize() {
    let w = $(window).width();
    let wLeftList_4 = 520; // 订单明细左边列表固定宽度
    $("#divH42").css({width: w - wLeftList_4 - 17});
    $("#divD42").css({left: -1, width: w - wLeftList_4 - 16});
}
